# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytorch_lightning as pl
from pytorch_lightning.plugins.precision.apex_amp import ApexMixedPrecisionPlugin
from pytorch_lightning.utilities import _APEX_AVAILABLE


if _APEX_AVAILABLE:
    from apex import amp


class NpuMixedPrecisionPlugin(ApexMixedPrecisionPlugin):

    precision = 16
    
    def __init__(self, loss_scale: float = None, amp_level: str = "O2") -> None:
        super().__init__(amp_level)
        self.loss_scale = loss_scale

    def dispatch(self, trainer: "pl.Trainer") -> None:
        if not self._connected:
            if self.loss_scale is not None:
                strategy = trainer.strategy
                _, strategy.optimizers = amp.initialize(
                    trainer.lightning_module, strategy.optimizers, opt_level=self.amp_level, loss_scale=self.loss_scale
                )
                self._connected = True
            else:
                return super().dispatch(trainer)
        return super(ApexMixedPrecisionPlugin, self).dispatch(trainer)